import webapp2
import datetime
import re

from google.appengine.ext import db

class Dish(db.Model):
	title = db.StringProperty(multiline=True)
	date = db.DateProperty()

class Comment(db.Model):
	content = db.StringProperty(multiline=True)
	date = db.DateTimeProperty(auto_now_add=True)
	
class Rating(db.Model):
	rate = db.RatingProperty()

class CommentPage(webapp2.RequestHandler):
	def get(self):
		dish_title = self.request.get('dish_title')
		dish_date_string = self.request.get('dish_date')
		comment_content = self.request.get('content')

		dish_date = datetime.datetime.strptime(dish_date_string, '%Y-%m-%d').date()

		dish = Dish(key_name = dish_title + dish_date_string, title = dish_title, date = dish_date)  
		comment = Comment(parent=dish, content=comment_content)

		comment.put()

class RatingPage(webapp2.RequestHandler):
	def get(self):
		dish_title = self.request.get('dish_title')
		dish_date_string = self.request.get('dish_date')
		dish_date = datetime.datetime.strptime(dish_date_string, '%Y-%m-%d').date()

		dish = Dish(key_name = dish_title + dish_date_string, title = dish_title, date = dish_date)
		rate = int(self.request.get('rate'))

		rating = Rating(parent=dish, rate=rate)

		rating.put()

class GetComment(webapp2.RequestHandler):
	def get(self):
		dish_title = self.request.get('dish_title')
		dish_date = self.request.get('dish_date')

		k = db.Key.from_path('Dish', dish_title + dish_date)

		query = db.Query(Comment)
		query.ancestor(k)
		query.order('-date')

		result = query.fetch(10)

		for comment in result:
			self.response.write(comment.content + '||' + str(comment.date) + '&&')
	        
class GetRating(webapp2.RequestHandler):
	def get(self):
		dish_title = self.request.get('dish_title')
		dish_date = self.request.get('dish_date')

		k = db.Key.from_path('Dish', dish_title + dish_date)

		query = db.Query(Rating)
		query.ancestor(k)

		count = 0
		sum = 0

		for rating in query:
			count = count + 1
			sum = sum + rating.rate	    

		self.response.write(sum / float(count))
	        
	        

app = webapp2.WSGIApplication([
	('/comment', CommentPage),
	('/rating', RatingPage),
	('/get_comment', GetComment),
	('/get_rating', GetRating),
], debug=True)

def main():
	app.run()
	
if __name__ == "__main__":
	main()